package com.zhy.generator.codegen.mybatis.xmlmapper.element;
import com.zhy.generator.codegen.api.IntrospectedColumn;
import com.zhy.generator.codegen.dom.xml.Attribute;
import com.zhy.generator.codegen.dom.xml.TextElement;
import com.zhy.generator.codegen.dom.xml.XmlElement;
import com.zhy.generator.codegen.mybatis.MyBatis3FormattingUtilities;
import com.zhy.generator.codegen.mybatis.xmlmapper.XmlElementIdConstant;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 *
 * @author Jeff Butler
 *
 */
public class DeleteByPrimaryKeyElementGenerator extends AbstractXmlElementGenerator {

    private boolean isSimple;

    public DeleteByPrimaryKeyElementGenerator(boolean isSimple) {
        super();
        this.isSimple = isSimple;
    }

    @Override
    public void addElements(XmlElement parentElement) {
        XmlElement answer = new XmlElement("delete"); //$NON-NLS-1$

        answer.addAttribute(new Attribute("id", XmlElementIdConstant.DELETE_BY_PRIMARYKEY)); //$NON-NLS-1$
        String parameterClass;
        if (!isSimple && introspectedTable.getRules().generatePrimaryKeyClass()) {
            parameterClass = introspectedTable.getPrimaryKeyType();
        } else {

            if (introspectedTable.getPrimaryKeyColumns().size() > 1) {
                parameterClass = "map"; //$NON-NLS-1$
            } else {
                parameterClass = introspectedTable.getPrimaryKeyColumns().get(0).getFullyQualifiedJavaType().toString();
            }
        }
        answer.addAttribute(new Attribute("parameterType",parameterClass));
        StringBuilder sb = new StringBuilder();
        sb.append("delete from "); //$NON-NLS-1$
        sb.append(introspectedTable.getIntrospectedTableName());
        sb.append(" where ");

        List<IntrospectedColumn> primaryKeyColumns = introspectedTable.getPrimaryKeyColumns();
        if(CollectionUtils.isEmpty(primaryKeyColumns)){
            return;
        }

        sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(primaryKeyColumns.get(0)));
        sb.append(" = #{pkid}"); //$NON-NLS-1$
        answer.addElement(new TextElement(sb.toString()));

        if (context.getPlugins().sqlMapDeleteByPrimaryKeyElementGenerated(answer,introspectedTable)) {
            parentElement.addElement(answer);
        }
    }
}
